package pdf

import (
	"bytes"
	"fmt"
	"image"
	"image/jpeg"
	"mytool/base"
	"os"
	"strconv"
	"strings"

	"github.com/signintech/gopdf"
	"golang.org/x/image/webp"
)

// imageToJPEGBytes 将image.Image转换为JPEG字节切片
func imageToJPEGBytes(img image.Image) ([]byte, error) {
	var buf bytes.Buffer
	// 这里可以使用"image/jpeg"包来将图像编码为JPEG
	// 注意：可能需要调整JPEG的质量参数
	if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 100}); err != nil {
		// if err := png.Encode(&buf, img); err != nil {
		return nil, fmt.Errorf("failed to encode image to jpeg: %v", err)
	}
	return buf.Bytes(), nil
}

// 1图片路径 2pdf路径
func img2Pdf(args []string) (err error) {
	imagePath := args[0]
	pdfPath := args[1]
	bleeding, bErr := strconv.ParseFloat(args[4], 64) //40.0 //出血值
	if bErr != nil {
		bleeding = 0.0
	}
	isWebp := strings.HasSuffix(strings.ToLower(imagePath), ".webp")

	file, err := os.Open(imagePath)
	if err != nil {
		fmt.Println("Error opening image:", err)
		return
	}
	defer file.Close()
	pdf := gopdf.GoPdf{}
	if isWebp {
		img, _ := webp.Decode(file)
		var w, h = float64(img.Bounds().Dx()), float64(img.Bounds().Dy())
		pdf.Start(gopdf.Config{PageSize: gopdf.Rect{W: w + bleeding*2, H: h + bleeding*2}})
		pdf.AddPage()
		jpegData, err := imageToJPEGBytes(img)
		// fmt.Print(jpegData)
		if err != nil {
			panic(err)
		}
		imgHolder2, err2 := gopdf.ImageHolderByBytes(jpegData)
		if err2 != nil {
			panic(err2)
		}
		pdf.ImageByHolder(imgHolder2, bleeding, bleeding, &gopdf.Rect{W: w, H: h})
	} else {
		img, _, _ := image.DecodeConfig(file)

		pdf.Start(gopdf.Config{PageSize: gopdf.Rect{W: float64(img.Width) + bleeding*2, H: float64(img.Height) + bleeding*2}})
		pdf.AddPage()
		imgHolder2, err2 := gopdf.ImageHolderByPath(imagePath)
		if err2 != nil {
			panic(err2)
		}
		pdf.ImageByHolder(imgHolder2, bleeding, bleeding, &gopdf.Rect{W: float64(img.Width), H: float64(img.Height)})
	}
	pdf.WritePdf(pdfPath)
	fmt.Print("1")
	return nil

}

// 2文件夹路径 3范围 eg:150 4 pdf路径 4 出血
func img2PdfByPath(args []string) (err error) {
	dirPath := args[0]
	rangeNum, rangeStrErr := strconv.ParseInt(args[1], 10, 64)
	pdfPath := args[2]
	bleeding, bErr := strconv.ParseFloat(args[3], 64) //40.0 //出血值
	if rangeStrErr != nil {
		fmt.Println("range error", rangeStrErr)
		return
	}
	if bErr != nil {
		bleeding = 0.0
	}
	pdf := gopdf.GoPdf{}
	isInit := false
	for i := 1; i <= int(rangeNum); i++ {
		itemPath := dirPath + "/" + strconv.Itoa(i) + ".png"
		file, err := os.Open(itemPath)
		if err != nil {
			fmt.Println("Error opening image:", err)
			return nil
		}
		defer file.Close()
		img, _, err := image.DecodeConfig(file)
		rect := gopdf.Rect{W: float64(img.Width) + bleeding*2, H: float64(img.Height) + bleeding*2}
		if isInit == false {
			pdf.Start(gopdf.Config{PageSize: rect})
			isInit = true
		}
		pdf.AddPageWithOption(gopdf.PageOption{PageSize: &rect})
		imgHolder2, err2 := gopdf.ImageHolderByPath(itemPath)
		if err2 != nil {
			panic(err2)
		}
		pdf.ImageByHolder(imgHolder2, bleeding, bleeding, &gopdf.Rect{W: float64(img.Width), H: float64(img.Height)})
	}
	// fmt.Println("开始转，" + imagePath + "->" + pdfPath)
	pdf.WritePdf(pdfPath)
	fmt.Print("1")
	return nil
}

func Img2PdfTools() []*base.Option {
	return []*base.Option{
		&base.Option{"img2Pdf", img2Pdf, `img2Pdf`},
		&base.Option{"img2PdfByPath", img2PdfByPath, `img2PdfByPath`},
	}
}
